package com.firefighting.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.firefighting.dao.BuildingMapper;
import com.firefighting.dao.ContractMaintenanceProjectMapper;
import com.firefighting.dao.ContractMapper;
import com.firefighting.dao.MaintenancePlanMapper;
import com.firefighting.dao.MaintenanceTestContentMapper;
import com.firefighting.dao.MaintenanceplanContentMapper;
import com.firefighting.dao.TaskMapper;
import com.firefighting.dao.UserMapper;
import com.firefighting.entity.Contract;
import com.firefighting.entity.ContractMaintenanceProject;
import com.firefighting.entity.MaintenancePlan;
import com.firefighting.entity.MaintenanceTestContent;
import com.firefighting.entity.MaintenanceplanContent;
import com.firefighting.entity.MonthPlanInfo;
import com.firefighting.entity.PlanListInfo;
import com.firefighting.entity.SeasonPlanInfo;
import com.firefighting.entity.Task;
import com.firefighting.entity.YearPlanInfo;
import com.firefighting.util.ContractTimeLimit;

@Service
public class MaintenancePlanService {
	@Autowired
	private ContractMapper contractMapper;
	@Autowired
	private MaintenancePlanMapper maintenancePlanMapper;
	@Autowired
	private MaintenanceplanContentMapper maintenancePlanContentMapper;
	@Autowired
	private MaintenanceTestContentMapper maintenanceTestContentMapper;
	@Autowired
	private TaskMapper taskMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ContractMaintenanceProjectMapper contractMaintenanceProjectMapper;
	@Autowired
	private BuildingMapper buildingMapper;
	/**
	 * @author Liuxc
	 * 
	 * 自动生成计划
	 * */
	
	@Transactional(rollbackFor = Exception.class)
	public Boolean creatorPlanUtilAndUpdateMaintenance(Integer contractId, int[] checkedIdArray){
		System.out.println("create");
		updateMantananceInContract(contractId,checkedIdArray);//更新维保内容
		deleteByContractId(contractId);//删除该合同所有计划
		createSeasonPlan(contractId, checkedIdArray);//生成季计划
		createYearPlan(contractId,checkedIdArray);//生成年计划
		createMonthPlan(contractId,checkedIdArray);//生成月计划
	    
		return true;
	}
	/**
	 * @author Liuxc 
	 * 
	 * 生成年计划
	 * */
	public void createYearPlan(Integer contractId, int[] checkedIdArray){
		// TODO Auto-generated method stub
		List<Integer> buildingIdList = new ArrayList<Integer>();
		buildingIdList = buildingMapper.selectBuildingIdByContract(contractId);
		int buildingNum = buildingMapper.getNumberOfContract(contractId);
		Calendar startTime = Calendar.getInstance();
		Calendar endTime = Calendar.getInstance();
		Contract contract = contractMapper.selectByPrimaryKey(contractId);
		startTime.setTime(contract.getSignDate());;
		endTime.setTime(contract.getEndDate());
		int excutorId = userMapper.getUserIdByUsername(contract.getProjectLeaderAccount()).getUserid();
		int startYear = ContractTimeLimit.getStartYear(startTime);//合同开始年
		int endYear = ContractTimeLimit.getEndYear(endTime);//合同结束年
		
		if(startYear <= endYear){
			Calendar calendar = Calendar.getInstance();  
		    Date time = calendar.getTime();  
		  //生成年计划
			for(int year = startYear; year <= endYear; year++){
				
				//插入计划

				MaintenancePlan maintenanceplan = new MaintenancePlan();
//				String planName = contract.getProjectName()+year+"年计划";
				String planName = year+"年计划";
				maintenanceplan.setPlanName(planName);
				maintenanceplan.setContractId(contractId);
				maintenanceplan.setFinishedNumber(0);
				maintenanceplan.setIsReport(false);
				maintenanceplan.setStartTime(time);
				maintenanceplan.setPlanType(3);
				maintenanceplan.setExecutorId(excutorId);
				maintenanceplan.setPlanExecuteTime(year+"12");//
				maintenancePlanMapper.insertSelective(maintenanceplan);
				System.out.println("after "+maintenanceplan.getId());
				//生成计划中的维保项目
				int planId = maintenanceplan.getId();
				int countNumber = 0;
				for(int id : checkedIdArray){//年计划包含所有维保项目
					List<MaintenanceTestContent> MaintenanceTestContentList = new ArrayList<MaintenanceTestContent>();
					MaintenanceTestContentList = maintenanceTestContentMapper.selectBySecondId(id);
					for(MaintenanceTestContent item : MaintenanceTestContentList){
						MaintenanceplanContent maintenancePlanContent = new MaintenanceplanContent();
						maintenancePlanContent.setMaintenanceplanId(planId);
						maintenancePlanContent.setMaintenanceContentId(item.getId());
						maintenancePlanContent.setStateFinished("未完成");
						maintenancePlanContent.setDevelopment("未下发");
						for(int buildingId : buildingIdList){
							maintenancePlanContent.setBuildingId(buildingId);
							maintenancePlanContentMapper.insert(maintenancePlanContent);
						}
						countNumber++;
					}
				}
				maintenanceplan.setTotalNumber(countNumber*buildingNum);
				maintenanceplan.setUndeliveredNumber(countNumber*buildingNum);
				maintenanceplan.setUnfinishedNumber(countNumber*buildingNum);
				maintenancePlanMapper.updateByPrimaryKeySelective(maintenanceplan);
				
				
			}
		}
		

	}

	/**
	 * @author Liuxc
	 * 生成季计划         //季度
	 * */
	public void createSeasonPlan(Integer contractId, int[] checkedIdArray){
		System.out.println("生成季度计划");
		List<Integer> buildingIdList = new ArrayList<Integer>();
		buildingIdList = buildingMapper.selectBuildingIdByContract(contractId);
		int buildingNum = buildingMapper.getNumberOfContract(contractId);	
		Calendar calendar = Calendar.getInstance();  
	    Date time = calendar.getTime();  
		Calendar startTime = Calendar.getInstance();
		Calendar endTime = Calendar.getInstance();
		Contract contract = contractMapper.selectByPrimaryKey(contractId);
		startTime.setTime(contract.getSignDate());
		endTime.setTime(contract.getEndDate());
		int excutorId = userMapper.getUserIdByUsername(contract.getProjectLeaderAccount()).getUserid();
		int startYear = startTime.get(Calendar.YEAR);//合同开始年
		int endYear = endTime.get(Calendar.YEAR);//合同结束年
    	int startMonth = ContractTimeLimit.getStartMonth(startTime);//合同开始月
		int endMonth = ContractTimeLimit.getEndMonth(endTime);//合同结束月
		int calDiffMonth = ContractTimeLimit.calDiffMonth(startTime, endTime);
		System.out.println("相差月："+calDiffMonth);
		System.out.println("startYear  "+startYear+"endYear  "+endYear);
		if(calDiffMonth >= 3){//如果合同时间大于3月，生成月计划
			for(int year = startYear; year <= endYear; year++){
				int month = startMonth;
				if(year > startYear){
					month = 1;
				}
				System.out.println("year is :" +year);
				if(year < endYear){
					int startSeason = judgeSeason(month);
					for(int i = startSeason ; i <= 4 ; i++){
						//生成季度计划
						MaintenancePlan maintenanceplan = new MaintenancePlan();
						/*String planName = contract.getProjectName()+year+"年第"+i+"季度计划";*/
						String planName = year+"年第"+i+"季度计划";
						maintenanceplan.setPlanName(planName);
						maintenanceplan.setContractId(contractId);
						maintenanceplan.setFinishedNumber(0);
						maintenanceplan.setIsReport(false);
						maintenanceplan.setStartTime(time);
						maintenanceplan.setPlanType(2);
						maintenanceplan.setExecutorId(excutorId);
						if(i < 4){
							maintenanceplan.setPlanExecuteTime(year+"0"+i*3);
						}else if(i == 4){
							maintenanceplan.setPlanExecuteTime(year+"12");
						}
						
						maintenancePlanMapper.insertSelective(maintenanceplan);
						//生成计划中的维保项目
						int planId = maintenanceplan.getId();
						int countNumber = 0;
						for(int id : checkedIdArray){//季度计划包含所有维保项目
							List<MaintenanceTestContent> MaintenanceTestContentList = new ArrayList<MaintenanceTestContent>();
							MaintenanceTestContentList = maintenanceTestContentMapper.selectBySecondId(id);
							for(MaintenanceTestContent item : MaintenanceTestContentList){
								String frequency = item.getFrequency();
								if(frequency.equals("每月")||frequency.equals("每周")||frequency.equals("每日")||frequency.equals("每季")){
									MaintenanceplanContent maintenancePlanContent = new MaintenanceplanContent();
									maintenancePlanContent.setMaintenanceplanId(planId);
									maintenancePlanContent.setMaintenanceContentId(item.getId());
									maintenancePlanContent.setStateFinished("未完成");
									maintenancePlanContent.setDevelopment("未下发");
									for(int buildingId : buildingIdList){
										maintenancePlanContent.setBuildingId(buildingId);
										maintenancePlanContentMapper.insert(maintenancePlanContent);
									}
									
									countNumber++;
								}
							}
						}
						
						maintenanceplan.setTotalNumber(countNumber*buildingNum);
						maintenanceplan.setUndeliveredNumber(countNumber*buildingNum);
						maintenanceplan.setUnfinishedNumber(countNumber*buildingNum);
						maintenancePlanMapper.updateByPrimaryKeySelective(maintenanceplan);
						
					}
				}else{
					int startSeason = judgeSeason(month);
					int endSeason = judgeSeason(endMonth);
					System.out.println("startSeason  "+startSeason+"endSeason  "+endSeason);
					for(int i = startSeason ; i <= endSeason ; i++){
						//生成季度计划
						MaintenancePlan maintenanceplan = new MaintenancePlan();
//						String planName = contract.getProjectName()+year+"年第"+i+"季度计划";
						String planName = year+"年第"+i+"季度计划";
						maintenanceplan.setPlanName(planName);
						maintenanceplan.setContractId(contractId);
						maintenanceplan.setFinishedNumber(0);
						maintenanceplan.setIsReport(false);
						maintenanceplan.setStartTime(time);
						maintenanceplan.setPlanType(2);
						maintenanceplan.setExecutorId(excutorId);
						if(i < 4){
							maintenanceplan.setPlanExecuteTime(year+"0"+i*3);
						}else if(i == 4){
							maintenanceplan.setPlanExecuteTime(year+"12");
						}
						maintenancePlanMapper.insertSelective(maintenanceplan);
						//生成计划中的维保项目
						int planId = maintenanceplan.getId();
						int countNumber = 0;
						for(int id : checkedIdArray){//季度计划包含所有维保项目
							List<MaintenanceTestContent> MaintenanceTestContentList = new ArrayList<MaintenanceTestContent>();
							MaintenanceTestContentList = maintenanceTestContentMapper.selectBySecondId(id);
							for(MaintenanceTestContent item : MaintenanceTestContentList){
								String frequency = item.getFrequency();
								if(frequency.equals("每月")||frequency.equals("每周")||frequency.equals("每日")||frequency.equals("每季")){
									MaintenanceplanContent maintenancePlanContent = new MaintenanceplanContent();
									maintenancePlanContent.setMaintenanceplanId(planId);
									maintenancePlanContent.setMaintenanceContentId(item.getId());
									maintenancePlanContent.setStateFinished("未完成");
									maintenancePlanContent.setDevelopment("未下发");
									for(int buildingId : buildingIdList){
										maintenancePlanContent.setBuildingId(buildingId);
										maintenancePlanContentMapper.insert(maintenancePlanContent);
									}
									countNumber++;
								}
							}
						}
						maintenanceplan.setTotalNumber(countNumber*buildingNum);
						maintenanceplan.setUndeliveredNumber(countNumber*buildingNum);
						maintenanceplan.setUnfinishedNumber(countNumber*buildingNum);
						maintenancePlanMapper.updateByPrimaryKeySelective(maintenanceplan);
					}
				}
			}
		}
	}
	
	
	/***
	 * Liuxc 生成月计划
	 * @param contractId
	 * @param checkedIdArray
	 * @throws Exception
	 */
	public void createMonthPlan(Integer contractId, int[] checkedIdArray){		
		// TODO Auto-generated method stub				
		System.out.println("生成月计划");
		List<Integer> buildingIdList = new ArrayList<Integer>();
		buildingIdList = buildingMapper.selectBuildingIdByContract(contractId);
		int buildingNum = buildingMapper.getNumberOfContract(contractId);
		Calendar startTime = Calendar.getInstance();
		Calendar endTime = Calendar.getInstance();
		Contract contract = contractMapper.selectByPrimaryKey(contractId);
		startTime.setTime(contract.getSignDate());
		endTime.setTime(contract.getEndDate());
		int excutorId = userMapper.getUserIdByUsername(contract.getProjectLeaderAccount()).getUserid();
		int startYear = startTime.get(Calendar.YEAR);//合同开始年
		int endYear = endTime.get(Calendar.YEAR);//合同结束年
/*		int startMonth = startTime.get(Calendar.MONTH)+1;//合同开始月
		int endMonth = endTime.get(Calendar.MONTH)+1;//合同结束月
*/		int startmonth = ContractTimeLimit.getStartMonth(startTime);
		int endmonth = ContractTimeLimit.getEndMonth(endTime);
		System.out.println("month is  "+startmonth);
		Calendar calendar = Calendar.getInstance();  
	    Date time = calendar.getTime();  
		for(int year = startYear; year <= endYear; year++){
			int month = startmonth;
			if(year > startYear){
				month = 1;
			}
			if(year < endYear){
				for(; month <= 12 ; month++){
					
					MaintenancePlan maintenanceplan = new MaintenancePlan();
//					String planName = contract.getProjectName()+year+"年"+month+"月计划";
					String planName = year+"年"+month+"月计划";
					maintenanceplan.setPlanName(planName);
					maintenanceplan.setContractId(contractId);
					maintenanceplan.setFinishedNumber(0);
					maintenanceplan.setIsReport(false);
					maintenanceplan.setStartTime(time);
					maintenanceplan.setPlanType(1);
					maintenanceplan.setExecutorId(excutorId);
					if(month < 10){
						maintenanceplan.setPlanExecuteTime(year+"0"+month);
					}else{
						maintenanceplan.setPlanExecuteTime(year+""+month);
					}
					maintenancePlanMapper.insertSelective(maintenanceplan);
					
					//生成计划中的维保项目
					int planId = maintenanceplan.getId();
					int countNumber = 0;
					for(int id : checkedIdArray){//月计划包含所有维保项目
						List<MaintenanceTestContent> MaintenanceTestContentList = new ArrayList<MaintenanceTestContent>();
						MaintenanceTestContentList = maintenanceTestContentMapper.selectBySecondId(id);
						for(MaintenanceTestContent item : MaintenanceTestContentList){
							String frequency = item.getFrequency();
							if(frequency.equals("每月")||frequency.equals("每周")||frequency.equals("每日")){
								MaintenanceplanContent maintenancePlanContent = new MaintenanceplanContent();
								maintenancePlanContent.setMaintenanceplanId(planId);
								maintenancePlanContent.setMaintenanceContentId(item.getId());
								maintenancePlanContent.setStateFinished("未完成");
								maintenancePlanContent.setDevelopment("未下发");
								for(int buildingId : buildingIdList){
									maintenancePlanContent.setBuildingId(buildingId);
									maintenancePlanContentMapper.insert(maintenancePlanContent);
								}
								countNumber++;
							}else if(frequency.equals("冬季每天")){
								 if(month > 9){
									MaintenanceplanContent maintenancePlanContent = new MaintenanceplanContent();
									maintenancePlanContent.setMaintenanceplanId(planId);
									maintenancePlanContent.setMaintenanceContentId(item.getId());
									maintenancePlanContent.setStateFinished("未完成");
									maintenancePlanContent.setDevelopment("未下发");
									for(int buildingId : buildingIdList){
										maintenancePlanContent.setBuildingId(buildingId);
										maintenancePlanContentMapper.insert(maintenancePlanContent);
									}
									countNumber++;
								 }
							}
						}
					}
					maintenanceplan.setTotalNumber(countNumber*buildingNum);
					maintenanceplan.setUndeliveredNumber(countNumber*buildingNum);
					maintenanceplan.setUnfinishedNumber(countNumber*buildingNum);
					maintenancePlanMapper.updateByPrimaryKeySelective(maintenanceplan);
				}
			}else{
				for(; month <= endmonth ; month++){
					MaintenancePlan maintenanceplan = new MaintenancePlan();
//					String planName = contract.getProjectName()+year+"年"+month+"月计划";
					String planName = year+"年"+month+"月计划";
					maintenanceplan.setPlanName(planName);
					maintenanceplan.setContractId(contractId);
					maintenanceplan.setFinishedNumber(0);
					maintenanceplan.setIsReport(false);
					maintenanceplan.setStartTime(time);
					maintenanceplan.setPlanType(1);
					maintenanceplan.setExecutorId(excutorId);
					if(month < 10){
						maintenanceplan.setPlanExecuteTime(year+"0"+month);
					}else{
						maintenanceplan.setPlanExecuteTime(year+""+month);
					}
				    maintenancePlanMapper.insertSelective(maintenanceplan);
					
					//生成计划中的维保项目
					int planId = maintenanceplan.getId();
					int countNumber = 0;
					for(int id : checkedIdArray){//月计划包含所有维保项目
						List<MaintenanceTestContent> MaintenanceTestContentList = new ArrayList<MaintenanceTestContent>();
						MaintenanceTestContentList = maintenanceTestContentMapper.selectBySecondId(id);
						for(MaintenanceTestContent item : MaintenanceTestContentList){
							String frequency = item.getFrequency();
							if(frequency.equals("每月")||frequency.equals("每周")||frequency.equals("每日")){
								MaintenanceplanContent maintenancePlanContent = new MaintenanceplanContent();
								maintenancePlanContent.setMaintenanceplanId(planId);
								maintenancePlanContent.setMaintenanceContentId(item.getId());
								maintenancePlanContent.setStateFinished("未完成");
								maintenancePlanContent.setDevelopment("未下发");
								for(int buildingId : buildingIdList){
									maintenancePlanContent.setBuildingId(buildingId);
									maintenancePlanContentMapper.insert(maintenancePlanContent);
								}
								countNumber++;
							}else if(frequency.equals("冬季每天")){
								 if(month > 0){
									MaintenanceplanContent maintenancePlanContent = new MaintenanceplanContent();
									maintenancePlanContent.setMaintenanceplanId(planId);
									maintenancePlanContent.setMaintenanceContentId(item.getId());
									maintenancePlanContent.setStateFinished("未完成");
									maintenancePlanContent.setDevelopment("未下发");
									for(int buildingId : buildingIdList){
										maintenancePlanContent.setBuildingId(buildingId);
										maintenancePlanContentMapper.insert(maintenancePlanContent);
									}
									countNumber++;
								 }
							}
							
						}
					}
					maintenanceplan.setTotalNumber(countNumber*buildingNum);
					maintenanceplan.setUndeliveredNumber(countNumber*buildingNum);
					maintenanceplan.setUnfinishedNumber(countNumber*buildingNum);
					maintenancePlanMapper.updateByPrimaryKeySelective(maintenanceplan);
				}
			}
		}
	}
	/**
	 * @author Liuxc
	 * 删除计划与维保项目关系
	 * */
	public void deleteByContractId(Integer contractId){
		// TODO Auto-generated method stub
		List<Integer> planIdList = new ArrayList<Integer>();
		planIdList = maintenancePlanMapper.selectByContractId(contractId);

		if(!planIdList.isEmpty()){
			maintenancePlanContentMapper.deleteByPlanId(planIdList);//删除计划中的维保项目 
		}
		
		maintenancePlanMapper.deleteByContractId(contractId);//删除合同中的计划
	}
	
	/** zhyan 查询维保计划数量列表 */
	@SuppressWarnings("rawtypes")
	public List<HashMap> selectMaintenancePlanList()
	{
		return maintenancePlanMapper.selectMaintenancePlanList();
	}
	
	/** zhyan 查询合同内的计划的详细信息 */
	@SuppressWarnings("rawtypes")
	public List<HashMap> queryPlanInfoByContractId(int id)
	{
		return maintenancePlanMapper.selectPlanInfoByContractId(id);
	}
	
	/** zhyan 根据合同中的计划的id删除已有计划 */
	public boolean isDeletePlan(int id)
	{
		return maintenancePlanMapper.deleteByContractId(id) > 0;
	}
	/** zhyan 根据计划id查询其所在的合同id */
	public int selectContractIdByPlanId(int id)
	{
		return maintenancePlanMapper.selectContractIdByPlanId(id);
	}
	
	/** zhyan 根据合同id列表查询对应的维保计划列表 */
	@SuppressWarnings("rawtypes")
	public List<HashMap> queryMaintenancePlanListByContractIdList(List<Integer> list)
	{
		return maintenancePlanMapper.selectMaintenancePlanByContractIdList(list);
	}
	
	/** zhyan 展示所有合同的月/季/年计划列表  */
	public List<PlanListInfo> getPlanListInfo()
	{
		List<PlanListInfo> result = new ArrayList<PlanListInfo>();
		List<PlanListInfo> tmp = new ArrayList<PlanListInfo>();
		List<MonthPlanInfo> month = maintenancePlanMapper.selectMonthPlanInfoList();
		List<SeasonPlanInfo> season = maintenancePlanMapper.selectSeasonPlanInfoList();
		List<YearPlanInfo> year = maintenancePlanMapper.selectYearPlanInfoList();
		
		tmp = MaintenancePlanService.addMonthPlanList(tmp,month);
		tmp = MaintenancePlanService.addSeasonPlanList(tmp, season);
		tmp = MaintenancePlanService.addYearPlanInfo(tmp, year);
		
		//排序
		Collections.sort(tmp, new Comparator<PlanListInfo>()
		{
			@Override
			public int compare(PlanListInfo o1, PlanListInfo o2)
			{
				if(o1.getContractId() > o2.getContractId())
					return 1;
				else if(o1.getContractId() < o2.getContractId())
					return -1;
				return 0;
			}
			
		});
		
		//如果只有一个元素，直接返回
		if(tmp.size() == 1)
		{
			return tmp;
		}
		else
		{
			int contractId = tmp.get(0).getContractId();
			
			int monthFinished = tmp.get(0).getMonthFinishedNumber();
			int monthUnfinished = tmp.get(0).getMonthUndeliveredNumber();
			int monthUndelivered = tmp.get(0).getMonthUndeliveredNumber();
			int seasonFinished = tmp.get(0).getSeasonFinishedNumber();
			int seasonUnfinished = tmp.get(0).getSeasonUnfinishedNumber();
			int seasonUndelivered = tmp.get(0).getSeasonUndeliveredNumber();
			int yearFinished = tmp.get(0).getYearFinishedNumber();
			int yearUnfinished = tmp.get(0).getYearUnfinishedNumber();
			int yearUndelivered = tmp.get(0).getYearUndeliveredNumber();
			
			for(int index = 1;index < tmp.size();index ++)
			{
				if(tmp.get(index).getContractId() == contractId)
				{
					PlanListInfo tmp2 = tmp.get(index);
					monthFinished += tmp2.getMonthFinishedNumber();
					monthUnfinished += tmp2.getMonthUnfinishedNumber();
					monthUndelivered += tmp2.getMonthUndeliveredNumber();
					
					seasonFinished += tmp2.getSeasonFinishedNumber();
					seasonUnfinished += tmp2.getSeasonUnfinishedNumber();
					seasonUndelivered += tmp2.getSeasonUndeliveredNumber();
					
					yearFinished += tmp2.getYearFinishedNumber();
					yearUnfinished += tmp2.getYearUnfinishedNumber();
					yearUndelivered += tmp2.getYearUndeliveredNumber();
				}
				
				if(tmp.get(index).getContractId() != contractId)
				{
					PlanListInfo element = new PlanListInfo();
					PlanListInfo original = tmp.get(index - 1);
					
					element.setContractId(contractId);
					element.setSignDate(original.getSignDate());
					element.setEndDate(original.getEndDate());
					element.setProjectName(original.getProjectName());
					
					element.setMonthFinishedNumber(monthFinished);
					element.setMonthUndeliveredNumber(monthUndelivered);
					element.setMonthUnfinishedNumber(monthUnfinished);
					
					element.setSeasonFinishedNumber(seasonFinished);
					element.setSeasonUndeliveredNumber(seasonUndelivered);
					element.setSeasonUnfinishedNumber(seasonUnfinished);
					
					element.setYearFinishedNumber(yearFinished);
					element.setYearUndeliveredNumber(yearUndelivered);
					element.setYearUnfinishedNumber(yearUnfinished);
					
					//添加到结果列表中
					result.add(element);
					//更新contractId值
					contractId = tmp.get(index).getContractId();
					
					monthFinished = 0;
					monthUnfinished = 0;
					monthUndelivered = 0;
					seasonFinished = 0;
					seasonUnfinished = 0;
					seasonUndelivered = 0;
					yearFinished = 0;
					yearUnfinished = 0;
					yearUndelivered = 0;
				}
				
				if(index == tmp.size() - 1)
				{
					PlanListInfo element = new PlanListInfo();
					PlanListInfo original = tmp.get(index);
					
					element.setContractId(contractId);
					element.setSignDate(original.getSignDate());
					element.setEndDate(original.getEndDate());
					element.setProjectName(original.getProjectName());
					
					element.setMonthFinishedNumber(monthFinished + original.getMonthFinishedNumber());
					element.setMonthUndeliveredNumber(monthUndelivered + original.getMonthUndeliveredNumber());
					element.setMonthUnfinishedNumber(monthUnfinished + original.getMonthUnfinishedNumber());
					
					element.setSeasonFinishedNumber(seasonFinished + original.getSeasonFinishedNumber());
					element.setSeasonUndeliveredNumber(seasonUndelivered + original.getSeasonUndeliveredNumber());
					element.setSeasonUnfinishedNumber(seasonUnfinished + original.getSeasonUnfinishedNumber());
					
					element.setYearFinishedNumber(yearFinished + original.getYearFinishedNumber());
					element.setYearUndeliveredNumber(yearUndelivered + original.getYearUndeliveredNumber());
					element.setYearUnfinishedNumber(yearUnfinished + original.getYearUnfinishedNumber());
					
					//添加到结果列表中
					result.add(element);
				}
			}
		}
		
		return result;
	}
	
	/** zhyan 根据合同id列表展示合同中的月/季/年计划列表 */
	public List<PlanListInfo> getPlanListInfoByContractIdList(List<Integer> contractIdList)
	{
		List<PlanListInfo> result = new ArrayList<PlanListInfo>();
		List<PlanListInfo> tmp = new ArrayList<PlanListInfo>();
		List<MonthPlanInfo> month = maintenancePlanMapper.selectMonthPlanInfoListByContractIdList(contractIdList);
		List<SeasonPlanInfo> season = maintenancePlanMapper.selectSeasonPlanInfoListByContractIdList(contractIdList);
		List<YearPlanInfo> year = maintenancePlanMapper.selectYearPlanInfoListByContractIdList(contractIdList);
		
		tmp = MaintenancePlanService.addMonthPlanList(tmp,month);
		tmp = MaintenancePlanService.addSeasonPlanList(tmp, season);
		tmp = MaintenancePlanService.addYearPlanInfo(tmp, year);
		
		//排序
		Collections.sort(tmp, new Comparator<PlanListInfo>()
		{
			@Override
			public int compare(PlanListInfo o1, PlanListInfo o2)
			{
				if(o1.getContractId() > o2.getContractId())
					return 1;
				else if(o1.getContractId() < o2.getContractId())
					return -1;
				return 0;
			}
			
		});
		
		//如果只有一个元素，直接返回
		if(tmp.size() == 0 || tmp.size() == 1 )
		{
			return tmp;
		}
		else
		{
			int contractId = tmp.get(0).getContractId();
			
			//int monthFinished = tmp.get(0).getMonthFinishedNumber();
			int monthUnfinished = 0;//tmp.get(0).getIsMonthFinished() > 0 ? 1 : 0;
			int monthUndelivered = 0;//tmp.get(0).getIsMonthDeliveredState();
			if(tmp.get(0).getMonthTotalNumber() != 0 && tmp.get(0).getMonthTotalNumber() == tmp.get(0).getMonthUndeliveredNumber())
				monthUndelivered ++;
			if(tmp.get(0).getMonthTotalNumber() > tmp.get(0).getMonthUndeliveredNumber() && tmp.get(0).getMonthTotalNumber() > tmp.get(0).getMonthFinishedNumber())
				monthUnfinished ++;
			
			//int seasonFinished = tmp.get(0).getSeasonFinishedNumber();
			int seasonUnfinished = 0;//tmp.get(0).getIsSeasonFinished() > 0 ? 1 : 0;
			int seasonUndelivered = 0;//tmp.get(0).getIsSeasonDeliveredState();
			if(tmp.get(0).getSeasonTotalNumber() != 0 && tmp.get(0).getSeasonTotalNumber() == tmp.get(0).getSeasonUndeliveredNumber())
				seasonUndelivered ++;
			if(tmp.get(0).getSeasonTotalNumber() > tmp.get(0).getSeasonUndeliveredNumber() && tmp.get(0).getSeasonTotalNumber() > tmp.get(0).getSeasonFinishedNumber())
				seasonUnfinished ++;
			
			//int yearFinished = tmp.get(0).getYearFinishedNumber();
			int yearUnfinished = 0;//tmp.get(0).getIsYearFinished();
			int yearUndelivered = 0;//tmp.get(0).getIsYearDeliveredState();
			if(tmp.get(0).getYearTotalNumber() != 0 && tmp.get(0).getYearTotalNumber() == tmp.get(0).getYearUndeliveredNumber())
				yearUndelivered ++;
			if(tmp.get(0).getYearTotalNumber() > tmp.get(0).getYearUndeliveredNumber() && tmp.get(0).getYearTotalNumber() > tmp.get(0).getYearFinishedNumber())
				yearUnfinished ++;
			
			for(int index = 1;index < tmp.size();index ++)
			{
				if(tmp.get(index).getContractId() == contractId)
				{
					PlanListInfo tmp2 = tmp.get(index);
					//monthFinished += tmp2.getMonthFinishedNumber();
					//monthUnfinished += tmp.get(0).getIsMonthFinished() > 0 ? 1 : 0;
					//monthUndelivered += tmp2.getIsMonthDeliveredState();
					if(tmp2.getMonthTotalNumber() != 0 && tmp2.getMonthTotalNumber() == tmp2.getMonthUndeliveredNumber())
						monthUndelivered ++;
					if(tmp2.getMonthTotalNumber() > tmp2.getMonthUndeliveredNumber() && tmp2.getMonthTotalNumber() > tmp2.getMonthFinishedNumber())
						monthUnfinished ++;
					
					//seasonFinished += tmp2.getSeasonFinishedNumber();
					//seasonUnfinished += tmp.get(0).getIsSeasonFinished() > 0 ? 1 : 0;
					//seasonUndelivered += tmp.get(0).getIsSeasonDeliveredState();
					if(tmp2.getSeasonTotalNumber() != 0 && tmp2.getSeasonTotalNumber() == tmp2.getSeasonUndeliveredNumber())
						seasonUndelivered ++;
					if(tmp2.getSeasonTotalNumber() > tmp2.getSeasonUndeliveredNumber() && tmp2.getSeasonTotalNumber() > tmp2.getSeasonFinishedNumber())
						seasonUnfinished ++;
					
					//yearFinished += tmp2.getYearFinishedNumber();
					
					//yearUnfinished += tmp.get(0).getIsYearFinished();
					//yearUndelivered += tmp.get(0).getIsYearDeliveredState();
					if(tmp2.getYearTotalNumber() != 0 && tmp2.getYearTotalNumber() == tmp2.getYearUndeliveredNumber())
						yearUndelivered ++;
					if(tmp2.getYearTotalNumber() > tmp2.getYearUndeliveredNumber() && tmp2.getYearTotalNumber() > tmp2.getYearFinishedNumber())
						yearUnfinished ++;
				}
				
				if(tmp.get(index).getContractId() != contractId)
				{
					PlanListInfo element = new PlanListInfo();
					index --;
					PlanListInfo original = tmp.get(index);
					
					element.setContractId(contractId);
					element.setSignDate(original.getSignDate());
					element.setEndDate(original.getEndDate());
					element.setProjectName(original.getProjectName());
					
					//element.setMonthFinishedNumber(monthFinished);
					element.setMonthUndeliveredNumber(monthUndelivered);
					element.setMonthUnfinishedNumber(monthUnfinished + monthUndelivered);
					
					//element.setSeasonFinishedNumber(seasonFinished);
					element.setSeasonUndeliveredNumber(seasonUndelivered);
					element.setSeasonUnfinishedNumber(seasonUnfinished + seasonUndelivered);
					
					//element.setYearFinishedNumber(yearFinished);
					element.setYearUndeliveredNumber(yearUndelivered);
					element.setYearUnfinishedNumber(yearUnfinished + yearUndelivered);
					
					//添加到结果列表中
					result.add(element);
					//更新contractId值
					contractId = tmp.get(index + 1).getContractId();
					
					//monthFinished = 0;
					monthUnfinished = 0;
					monthUndelivered = 0;
					//seasonFinished = 0;
					seasonUnfinished = 0;
					seasonUndelivered = 0;
					//yearFinished = 0;
					yearUnfinished = 0;
					yearUndelivered = 0;
				}
				
				if(index == tmp.size() - 1)
				{
					PlanListInfo element = new PlanListInfo();
					PlanListInfo original = tmp.get(index);
					
					element.setContractId(contractId);
					element.setSignDate(original.getSignDate());
					element.setEndDate(original.getEndDate());
					element.setProjectName(original.getProjectName());
					
					//月计划
					//element.setMonthFinishedNumber(monthFinished + original.getMonthFinishedNumber());
					if(element.getMonthTotalNumber() != 0 && element.getMonthTotalNumber() == element.getMonthUndeliveredNumber())
						monthUndelivered ++;
					if(element.getMonthTotalNumber() > element.getMonthUndeliveredNumber() && element.getMonthTotalNumber() > element.getMonthFinishedNumber())
						monthUnfinished ++;
					
					element.setMonthUndeliveredNumber(monthUndelivered);
					element.setMonthUnfinishedNumber(monthUnfinished + monthUndelivered);
					
					//季计划
					//element.setSeasonFinishedNumber(seasonFinished + original.getSeasonFinishedNumber());
					if(element.getSeasonTotalNumber() != 0 && element.getSeasonTotalNumber() == element.getSeasonUndeliveredNumber())
						seasonUndelivered ++;
					if(element.getSeasonTotalNumber() > element.getSeasonUndeliveredNumber() && element.getSeasonTotalNumber() > element.getSeasonFinishedNumber())
						seasonUnfinished ++;
					
					element.setSeasonUndeliveredNumber(seasonUndelivered);
					element.setSeasonUnfinishedNumber(seasonUnfinished + seasonUndelivered);
					
					//年计划
					//element.setYearFinishedNumber(yearFinished + original.getYearFinishedNumber());
					if(element.getYearTotalNumber() != 0 && element.getYearTotalNumber() == element.getYearUndeliveredNumber())
						yearUndelivered ++;
					if(element.getYearTotalNumber() > element.getYearUndeliveredNumber() && element.getYearTotalNumber() > element.getYearFinishedNumber())
						yearUnfinished ++;
					
					element.setYearUndeliveredNumber(yearUndelivered);
					element.setYearUnfinishedNumber(yearUnfinished + yearUndelivered);
					
					//添加到结果列表中
					result.add(element);
				}
			}
		}
		
		return result;
	}
	
	/** zhyan 将月计划信息添加到计划列表中 */
	private static List<PlanListInfo> addMonthPlanList(List<PlanListInfo> result, List<MonthPlanInfo> month)
	{
		for(MonthPlanInfo element : month)
		{
			PlanListInfo info = new PlanListInfo();
			
			info.setId(element.getId());
			info.setContractId(element.getContractId());
			info.setSignDate(element.getSignDate());
			info.setEndDate(element.getEndDate());
			info.setProjectName(element.getProjectName());
			info.setMonthTotalNumber(element.getTotalNumber());
			info.setMonthFinishedNumber(element.getMonthFinishedNumber());
			info.setMonthUndeliveredNumber(element.getMonthUndeliveredNumber());
			info.setMonthUnfinishedNumber(element.getMonthUnfinishedNumber());
			info.setIsMonthDeliveredState(element.getIsDeliveredState());
			info.setIsMonthFinished(element.getIsFinished());
			
			result.add(info);
		}
		
		return result;
	}
	
	/** zhyan 将季计划添加到计划列表中 */
	private static List<PlanListInfo> addSeasonPlanList(List<PlanListInfo> result, List<SeasonPlanInfo> season)
	{
		for(SeasonPlanInfo element : season)
		{
			PlanListInfo tmp = new PlanListInfo();
			
			tmp.setContractId(element.getContractId());
			tmp.setSignDate(element.getSignDate());
			tmp.setEndDate(element.getEndDate());
			tmp.setProjectName(element.getProjectName());
			tmp.setSeasonTotalNumber(element.getTotalNumber());
			tmp.setSeasonFinishedNumber(element.getSeasonFinishedNumber());
			tmp.setSeasonUndeliveredNumber(element.getSeasonUndeliveredNumber());
			tmp.setSeasonUnfinishedNumber(element.getSeasonUnfinishedNumber());
			tmp.setIsSeasonDeliveredState(element.getIsDeliveredState());
			tmp.setIsSeasonFinished(element.getIsFinished());
			
			result.add(tmp);
		}
		
		return result;
	}
	
	/** zhyan 将年计划添加到计划列表中 */
	private static List<PlanListInfo> addYearPlanInfo(List<PlanListInfo> result, List<YearPlanInfo> year)
	{
		for(YearPlanInfo element : year)
		{
			PlanListInfo tmp = new PlanListInfo();
			
			tmp.setContractId(element.getContractId());
			tmp.setSignDate(element.getSignDate());
			tmp.setEndDate(element.getEndDate());
			tmp.setProjectName(element.getProjectName());
			tmp.setYearTotalNumber(element.getTotalNumber());
			tmp.setYearFinishedNumber(element.getYearFinishedNumber());
			tmp.setYearUndeliveredNumber(element.getYearUndeliveredNumber());
			tmp.setYearUnfinishedNumber(element.getYearUnfinishedNumber());
			tmp.setIsYearDeliveredState(element.getIsDeliveredState());
			tmp.setIsYearFinished(element.getIsFinished());
			
			result.add(tmp);
		}
		
		return result;
	}

	/**
	 * @author Liuxc
	 * 
	 * 查询合同下是否已经有任务下发
	 * */
	public boolean IsContractHasTask(Integer contractId) {
		// TODO Auto-generated method stub
		List<Integer> planIdList = new ArrayList<Integer>();
		List<Task> taskList = new ArrayList<Task>();
		planIdList = maintenancePlanMapper.selectByContractId(contractId);
		if(planIdList.isEmpty()){
			return false;
		}else{
			taskList = taskMapper.selectByPlanIdList(planIdList);
			if(taskList.isEmpty()){
				return false;
			}else{
				return true;
			}
		}
		
		
	}
	
	/**
	 * @author Liuxc
	 * 判断季度
	 * */
	public int judgeSeason( int month){
		int season = 0;
		if(month <= 3){//第一季度开始
			season = 1;
		}else if(month > 3 && month <=6){//第二季度开始
			season = 2;
		}else if(month > 6 && month <=9){//第三季度开始
			season = 3;
		}else if(month > 9 && month <=12){//第四季度开始
			season = 4;
		}
		return season;
	}
	//Hanjd 根据计划id查询
	public MaintenancePlan queryByMantenancePlanId(Integer planId){
		return maintenancePlanMapper.selectByPrimaryKey(planId);
	}
	//Hanjd 根据planid查询项目内容
	public List<HashMap<String, Object>> selectMaintenanceList(Integer planId,Integer buildingId) {
		return maintenancePlanMapper.selectMaintenanceList(planId,buildingId);
	}
	//Hanjd 根据planid和建筑物id查询项目内容
	public List<HashMap<String, Object>> selectBuildingAlreadyMaintenanceList(Integer id,Integer buildingId){
		return maintenancePlanMapper.selectBuildingAlreadyMaintenanceList(id,buildingId);
	}
	public void updateMaintenanceplan(MaintenancePlan maintenanceplan) {
		// TODO Auto-generated method stub
        try{
        	maintenancePlanMapper.updateByPrimaryKeySelective(maintenanceplan);
        }catch(Exception e){
        	e.printStackTrace();
        	throw new RuntimeException("更新失败");
        }
		
	}		
	
    //更新合同中的维保项目
	public Boolean updateMantananceInContract(Integer contractId, int[] checkedIdArray) {
		// TODO Auto-generated method stub
		Boolean flag = true;
			contractMaintenanceProjectMapper.deleteByContractId(contractId);
			for(Integer item : checkedIdArray){
				ContractMaintenanceProject cmp = new ContractMaintenanceProject();
				cmp.setContractId(contractId);
				cmp.setMaintenanceId(item);
				contractMaintenanceProjectMapper.insert(cmp);
			}
		return flag;
	}
}
